package Leetcode;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class Trie {
    private Trie[] children;
    private boolean isEnd;
    public Trie(){
        children = new Trie[26];
        isEnd = false;
    }
    public void insert(String word) {
        Trie trie = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (trie.children[index] == null){
                trie.children[index] = new Trie();
            }
            trie = trie.children[index];
        }
        trie.isEnd = true;
    }
    public boolean search(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] != null){
                node = node.children[index];
            } else {
                return false;
            }
        }
        return node.isEnd;
    }
    public boolean startsWith(String prefix) {
        Trie node = this;
        for (int i = 0; i < prefix.length(); i++) {
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null){
                return false;
            }
            node = node.children[index];
        }
        return true;
    }
}
